<template>
  <view class="order-detail-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">订单详情</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <text>加载中...</text>
    </view>

    <!-- 订单内容 -->
    <view class="content" v-else-if="orderDetail">
      <!-- 订单状态 -->
      <view class="status-section">
        <view class="status-icon">
          <text v-if="orderDetail.status === 'pending'">⏰</text>
          <text v-else-if="orderDetail.status === 'preparing'">👨‍🍳</text>
          <text v-else-if="orderDetail.status === 'shipping'">🚚</text>
          <text v-else-if="orderDetail.status === 'delivered'">✅</text>
          <text v-else>📋</text>
        </view>
        <text class="status-text">{{ getStatusText(orderDetail.status) }}</text>
      </view>

      <!-- 用户信息 -->
      <view class="info-section">
        <text class="section-title">👤 用户信息</text>
        <view class="info-row">
          <text class="info-label">姓名</text>
          <text class="info-value">{{ orderDetail.user.name }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">电话</text>
          <text class="info-value">{{ orderDetail.user.phone }}</text>
        </view>
      </view>

      <!-- 配送信息 -->
      <view class="info-section">
        <text class="section-title">📍 配送信息</text>
        <view class="info-row">
          <text class="info-label">配送地址</text>
          <text class="info-value">{{ orderDetail.deliveryAddress }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">配送日期</text>
          <text class="info-value">{{ orderDetail.scheduledDeliveryDate }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">配送时间</text>
          <text class="info-value">{{ orderDetail.scheduledDeliveryTime }}</text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="info-section">
        <text class="section-title">🍱 商品列表</text>
        <view class="item-card" v-for="(item, index) in orderDetail.items" :key="index">
          <view class="item-info">
            <text class="item-name">{{ item.foodName }}</text>
            <text class="item-spec" v-if="item.spiceLevel">{{ item.spiceLevel }}</text>
          </view>
          <view class="item-price">
            <text class="item-quantity">x{{ item.quantity }}</text>
            <text class="item-amount">¥{{ item.price * item.quantity }}</text>
          </view>
        </view>
      </view>

      <!-- 费用明细 -->
      <view class="info-section">
        <text class="section-title">💰 费用明细</text>
        <view class="info-row">
          <text class="info-label">商品小计</text>
          <text class="info-value">¥{{ orderDetail.subtotal }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">配送费</text>
          <text class="info-value">¥{{ orderDetail.deliveryFee }}</text>
        </view>
        <view class="info-row total">
          <text class="info-label">订单总额</text>
          <text class="info-value price">¥{{ orderDetail.totalAmount }}</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="info-section">
        <text class="section-title">📝 订单信息</text>
        <view class="info-row">
          <text class="info-label">订单编号</text>
          <text class="info-value">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">下单时间</text>
          <text class="info-value">{{ orderDetail.createdAt }}</text>
        </view>
        <view class="info-row" v-if="orderDetail.notes">
          <text class="info-label">备注</text>
          <text class="info-value">{{ orderDetail.notes }}</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="actions-section" v-if="shouldShowActions">
        <!-- 待接单状态（pending=待支付，paid=已支付待接单）-->
        <template v-if="orderDetail.status === 'pending' || orderDetail.status === 'paid'">
          <button class="action-btn reject" @click="rejectOrder">拒绝订单</button>
          <button class="action-btn accept" @click="acceptOrder">接受订单</button>
        </template>

        <!-- 备货中状态（接单后自动变为此状态）-->
        <template v-if="orderDetail.status === 'preparing'">
          <button class="action-btn primary full" @click="startShipping">开始配送</button>
        </template>
      </view>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import merchantService from '../../../services/merchant.js'
import { smartBack } from '../../../utils/navigation.js'
import CustomModal from '../../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      orderId: null,
      loading: false,
      orderDetail: null
    }
  },
  computed: {
    shouldShowActions() {
      if (!this.orderDetail) return false
      return !['delivered', 'cancelled', 'refunded'].includes(this.orderDetail.status)
    }
  },
  onLoad(options) {
    this.getStatusBarHeight()
    
    if (options.id) {
      this.orderId = parseInt(options.id)
      this.loadOrderDetail()
    }
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      // 设置 CSS 变量，用于固定导航栏定位
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载订单详情
    async loadOrderDetail() {
      this.loading = true
      try {
        const response = await merchantService.getOrderDetail(this.orderId)
        const data = response.data
        
        console.log('订单详情原始数据:', data)
        
        // 格式化订单详情
        this.orderDetail = {
          id: data.id,
          orderNo: data.orderNo || data.order_no,
          status: data.status,
          user: {
            name: data.deliveryName || data.delivery_name || '收货人',
            phone: data.deliveryPhone || data.delivery_phone || ''
          },
          deliveryAddress: data.deliveryAddress || data.delivery_address || '',
          scheduledDeliveryDate: data.scheduledDeliveryDate || data.scheduled_delivery_date || '',
          scheduledDeliveryTime: data.scheduledDeliveryTime || data.scheduled_delivery_time || '',
          items: (data.items || []).map(item => ({
            foodName: item.foodName || item.food_name,
            quantity: item.quantity,
            price: item.foodPrice || item.food_price,
            spiceLevel: item.spiceLevel || item.spice_level
          })),
          subtotal: data.foodAmount || data.food_amount || 0,
          deliveryFee: data.deliveryFee || data.delivery_fee || 0,
          totalAmount: data.totalAmount || data.total_amount || 0,
          notes: data.notes || '',
          createdAt: data.createdAt || data.created_at || ''
        }
        
        console.log('订单详情格式化后:', this.orderDetail)
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 获取状态文本
    getStatusText(status) {
      return merchantService.getOrderStatusText(status)
    },

    // 接单
    async acceptOrder() {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '确认接单',
        content: `订单金额：¥${this.orderDetail.totalAmount}\n\n确认接受此订单吗？`,
        confirmText: '确认接单',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.acceptOrder(this.orderId)
              
              uni.showToast({
                title: '接单成功',
                icon: 'success'
              })
              
              // 刷新订单详情
              setTimeout(() => {
                this.loadOrderDetail()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '接单失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 拒单
    async rejectOrder() {
      this.$refs.customModal.show({
        type: 'warning',
        title: '拒绝订单',
        content: '确定要拒绝此订单吗？',
        confirmText: '确认拒绝',
        cancelText: '取消',
        showInput: true,
        inputPlaceholder: '请输入拒绝原因（选填）',
        onConfirm: async (inputValue) => {
            try {
              const reason = inputValue || '商家拒绝接单'
              await merchantService.rejectOrder(this.orderId, reason)
              
              uni.showToast({
                title: '已拒绝订单',
                icon: 'success'
              })
              
              // 刷新订单详情
              setTimeout(() => {
                this.loadOrderDetail()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 开始配送
    async startShipping() {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '开始配送',
        content: '确认开始配送吗？',
        confirmText: '开始配送',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.shipOrder(this.orderId)
              
              uni.showToast({
                title: '已开始配送',
                icon: 'success'
              })
              
              // 刷新订单详情
              setTimeout(() => {
                this.loadOrderDetail()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 返回
    goBack() {
      smartBack('/pages/merchant/orders/orders')
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 40rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

// 加载状态
.loading-container {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  text-align: center;
  padding: 120rpx 0;
  font-size: 28rpx;
  color: #999;
}

// 内容区域
.content {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  padding: 20rpx;
}

// 订单状态
.status-section {
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  margin-bottom: 20rpx;
}

.status-icon {
  font-size: 100rpx;
  margin-bottom: 20rpx;
}

.status-text {
  display: block;
  font-size: 32rpx;
  font-weight: 700;
  color: #fff;
}

// 信息区块
.info-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &.total {
    padding-top: 24rpx;
    margin-top: 16rpx;
    border-top: 2rpx solid #f0f0f0;
    border-bottom: none;
  }
}

.info-label {
  font-size: 26rpx;
  color: #666;
  min-width: 140rpx;
}

.info-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  text-align: right;

  &.price {
    font-size: 32rpx;
    font-weight: 700;
    color: #ff4757;
  }
}

// 商品卡片
.item-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-info {
  flex: 1;
}

.item-name {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.item-spec {
  display: inline-block;
  font-size: 22rpx;
  color: #ff8a00;
  padding: 2rpx 8rpx;
  background: #fff3e0;
  border-radius: 4rpx;
}

.item-price {
  text-align: right;
  margin-left: 20rpx;
}

.item-quantity {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.item-amount {
  display: block;
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

// 操作按钮
.actions-section {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  border: none;

  &.full {
    flex: none;
    width: 100%;
  }

  &.reject {
    background: #fff;
    color: #666;
    border: 2rpx solid #ddd;
  }

  &.accept,
  &.primary {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    color: #fff;
  }
}
</style>
